//
//  CarInfoViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 9/3/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation

typealias CarInfoFullCellConfigurator = TableCellConfigurator<CarInfoFullCell, MainViewModel.CarInfoItems?>
typealias CarGeneralInfoCellConfigurator = TableCellConfigurator<CarGeneralInfoCell, CarGeneralData?>

final class CarInfoViewModel {
    var items: [CellConfigurator] = []
    
    var delegate: ViewModelProtocol!
    
    var post: Post!
    
    private let backend = Backend()
    
    public func setUpCells () {
        let firstCell = CarInfoFullCellConfigurator(item: MainViewModel.CarInfoItems(car: post.car, city: post.city, ruleType: post.ruleType))
        items.append(firstCell)
        delegate.updatePosts()
    }
    
    private func addGeneralCell (generalData: CarGeneralData) {
        let cell = CarGeneralInfoCellConfigurator(item: generalData)
        items.append(cell)
        delegate.updatePosts()
    }
}


extension CarInfoViewModel {
    
    public func loadData () {
        if let number = post.car.carNumber {
            let requestURL = Request(base: .garage).getUrl(path: "garage/info/\(number.fullNumber)/")
            let request = URLRequest(url: requestURL)
            self.delegate.updateSpinner(showSpinner: true)
            
            backend.fetchFromBackend(for: CarGeneralData.self, request: request, statusCode: 200) { (result) in
                self.delegate.updateSpinner(showSpinner: false)
                switch result {
                case .failure(let err):
                    self.delegate.didHappenError(error: err)
                case .success(let carGeneralData):
                    self.addGeneralCell(generalData: carGeneralData)
                }
            }
        }
    }
}
